package com.apiz.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.apiz.model.User;
import com.apiz.utils.SignUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口
 */
public class ZApiClient {

    private String accessKey;

    private String secretKey;

    public static final String GATEWAY_HOST = "http://118.25.141.71:8090";

    private Map<String,String> getHeaderMap(String body){
        Map<String,String> hashMap = new HashMap<>();

        hashMap.put("accessKey",accessKey);
        //一定不能发送给后端
//        hashMap.put("secretKey",secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        hashMap.put("secretKey",secretKey);
        hashMap.put("timeStamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign", SignUtil.getSign(body,secretKey));

        return hashMap;
    }



    public ZApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String invokeHandler(String param,String url){
        String json = JSONUtil.toJsonStr(param);

        HttpResponse response = HttpRequest.post(url)
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(response.getStatus());

        System.out.println(response.body());

        return response.body();
    }

    public String getNameByGet(String name){

        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3= HttpUtil.get(GATEWAY_HOST+"/api/name/", paramMap);

        System.out.println(result3);

        return result3;
    }

    public String getNameByPost( String name){
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3= HttpUtil.post(GATEWAY_HOST+"/api/name/", paramMap);

        System.out.println(result3);

        return result3;
    }

    public String getUserNameByPost(User user){

        String json = JSONUtil.toJsonStr(user);

        HttpResponse response = HttpRequest.post(GATEWAY_HOST+"/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(response.getStatus());

        System.out.println(response.body());

        return response.body();
    }
}
